layui.define(['jquery','flow'],function(exports){

  var $ = layui.$;
  var flow = layui.flow;

  var obj = {
    loadSelect : function(id){
        var that = $(id);
        var dlId = id + '-dl';
        var search = that.attr("search");
        // keyword只在搜索模式生效
        var keyword = search ? that.val().trim() : "";
        $(dlId).unbind().on('mousedown','dd',function(){
            var value = $(this).attr("lay-value");
            var text = $(this).text();
            debug&&console.log(value,text);
            that.attr("data-value",value).attr("data-text",text).val(text);
            $(this).addClass('layui-this').siblings().removeClass('layui-this');
        }).next(".layui-flow-more").remove();
        flow.load({
            elem: dlId
            ,scrollElem: dlId
            ,mb: 400
            ,end: ' '
            ,done: function(page, next){
              var lis = [];
              $.ajax({
                    type: "GET",
                    url: "category/page",
                    data: {"pageNum": page,"pageSize": 20,"name":keyword},
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0) {
                            if(page == 1){
                                $(dlId).empty();
                            }
                            if(page == 1 && result.data.list.length == 0){
                                lis.push('<p class="layui-select-none">无匹配项</p>');
                            }
                            var value = that.attr("data-value");
                            $.each(result.data.list, function(index, item){
                                var text = escape(item.name);
                                var select = '';
                                if(!search){
                                    if(!value){
                                        if(page == 1 && index == 0){
                                            select = 'class="layui-this"';
                                            that.attr("data-value", item.id).attr("data-text", text).val(text);
                                        }
                                    }else if(value == item.id){
                                        select = 'class="layui-this"';
                                    }
                                }
                                var html = '<dd lay-value="'+ item.id +'" '+ select +'>'+ text +'</dd>';
                                lis.push(html);
                            });
                            next(lis.join(''), page < result.data.pages);
                        }
                    }
              });
            }
        });
    },
    initSelect : function(id){
        // 创建下拉框
        var that = $(id);
        var dlId = id + '-dl';
        var html = '';
        html += '<div class="layui-form-select">';
        html += '   <div class="layui-select-title">';
        html += that.attr("placeholder","请选择").prop("outerHTML");
        html += '       <i class="layui-edge"></i>';
        html += '   </div>';
        html += '   <dl id="' + dlId.replace("#","") + '" class="layui-anim layui-anim-upbit">';
        html += '       <p class="layui-select-none">无匹配项</p>';
        html += '   </dl>';
        html += '</div>';
        that.after(html).remove();
        that = $(id);
        // 绑定事件
        var searchTimer = null;
        that.on('focus',function(){
            var elem = that.val("").parent().parent().addClass('layui-form-selected');
            var top = elem.offset().top + elem.outerHeight() + 5 - $(window).scrollTop()
            var dlHeight = $(dlId).outerHeight();
            var wHeight = $(window).height();
            debug&&console.log(top,dlHeight,wHeight);
            if(top + dlHeight > wHeight && top >= dlHeight){
              elem.addClass('layui-form-selectup');
            }
        }).on('blur',function(){
            that.val(that.attr("data-text")).removeAttr("search").parent().parent().removeClass('layui-form-selected');
            obj.loadSelect(id);
        }).on('input',function(){
            clearTimeout(searchTimer); //输入清除定时器
            searchTimer = setTimeout(function () {
              that.attr("search",true);
              obj.loadSelect(id);
            },250);
        }).on("keydown", function (event) {
           if (event.key === "Enter") {
               var activeLi = $(dlId + " dd.active")[0];
               if(typeof activeLi !== "undefined"){
                   $(activeLi).trigger("mousedown");
               }
               that.blur();
                // 阻止默认浏览器动作(W3C)
                var e = event;
                if ( e && e.preventDefault )
                    e.preventDefault();
                // IE中阻止函数器默认动作的方式
                else
                    window.event.returnValue = false;
                return false;
           } else if (event.key === "ArrowDown") {
               var activeLi = $(dlId + " dd.active")[0];
               var list = $(dlId + " dd");
               if(typeof activeLi === "undefined"){
                   list.eq(0).addClass("active");
               }else{
                   var nextActiveLi;
                   var last;
                   list.each(function(index,item){
                       if($(item).hasClass("active")){
                           var nextIndex = index + 1;
                           nextActiveLi = list[nextIndex];
                           if(nextIndex + 1 === list.length){
                               last = true
                           }
                           return false;
                       }
                   });
                   if(typeof nextActiveLi !== "undefined"){
                       $(activeLi).removeClass("active");
                       $(nextActiveLi).addClass("active");
                       // 滚动
                       if(last){
                           $(dlId).animate({scrollTop: $(dlId)[0].scrollHeight}, 50);
                       }else{
                           elasticScroll(dlId, nextActiveLi.offsetTop);
                       }
                   }
               }
           } else if (event.key === "ArrowUp") {
               var activeLi = $(dlId + " dd.active")[0];
               var list = $(dlId + " dd");
               if(typeof activeLi === "undefined"){
                   list.eq(0).addClass("active");
               }else{
                   var nextActiveLi;
                   var first;
                   list.each(function(index,item){
                       if($(item).hasClass("active")){
                           var nextIndex = index - 1;
                           nextActiveLi = list[nextIndex];
                           if(nextIndex === 0){
                               first = true;
                           }
                           return false;
                       }
                   });
                   if(typeof nextActiveLi !== "undefined"){
                       $(activeLi).removeClass("active");
                       $(nextActiveLi).addClass("active");
                       // 滚动
                       if(first){
                           $(dlId).animate({scrollTop: 0}, 50);
                       }else{
                           elasticScroll(dlId, nextActiveLi.offsetTop);
                       }
                   }
               }
           } else if (event.key === "Backspace") {
               // 退出选择模式
               $(dlId + " dd.active").removeClass("active");
           }
       });
        // 加载数据
        obj.loadSelect(id);
    }
  };

  exports('categorySelect', obj);
});
